#!/bin/bash

# Staging数据库管理脚本
# 使用方法: ./staging-db-manager.sh [create|test|backup|restore|reset]

DB_HOST="rm-t4n2um727ltmubz.mysql.singapore.rds.aliyuncs.com"
DB_PORT="3306"
STAGING_DB_NAME="cumrbull_staging"
STAGING_DB_USER="cmb_staging"
STAGING_DB_PASS="Staging123!@#"

case "$1" in
    create)
        echo "🗄️ 创建Staging数据库..."
        mysql -h $DB_HOST -P $DB_PORT -u cmb_admin -p < ../create-staging-database.sql
        ;;
    test)
        echo "🧪 测试Staging数据库连接..."
        node ../test-staging-database.js
        ;;
    backup)
        echo "💾 备份Staging数据库..."
        BACKUP_FILE="staging_backup_$(date +%Y%m%d_%H%M%S).sql"
        mysqldump -h $DB_HOST -P $DB_PORT -u $STAGING_DB_USER -p$STAGING_DB_PASS $STAGING_DB_NAME > $BACKUP_FILE
        echo "备份已保存到: $BACKUP_FILE"
        ;;
    restore)
        if [ -z "$2" ]; then
            echo "请指定备份文件: $0 restore <backup_file>"
            exit 1
        fi
        echo "🔄 恢复Staging数据库..."
        mysql -h $DB_HOST -P $DB_PORT -u $STAGING_DB_USER -p$STAGING_DB_PASS $STAGING_DB_NAME < $2
        ;;
    reset)
        echo "⚠️ 重置Staging数据库（将删除所有数据）..."
        read -p "确认重置？(y/N): " confirm
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            mysql -h $DB_HOST -P $DB_PORT -u $STAGING_DB_USER -p$STAGING_DB_PASS -e "DROP DATABASE IF EXISTS $STAGING_DB_NAME; CREATE DATABASE $STAGING_DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
            echo "✅ Staging数据库已重置"
        else
            echo "取消重置操作"
        fi
        ;;
    *)
        echo "使用方法: $0 {create|test|backup|restore|reset}"
        exit 1
        ;;
esac
